package cn.ipenta.blockchain.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;

import net.sf.cglib.beans.BeanMap;

public class BeanUtils {

	public static <T> Map<?, ?> beanToJsonmap(T t) {
		return JSON.parseObject(JSON.toJSONString(t), HashMap.class);
	}

	public static <T> Map<String, String> beanTomap(T t) {

		Map<String, String> map = null;

		try {
			map = org.apache.commons.beanutils.BeanUtils.describe(t);
			map.remove("class");

		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	public static <T> T mapToBean(TreeMap<String, Object> map, T t) {
		BeanMap.create(t).putAll(map);
		return t;
	}

	// 简单对象转换
	public static <T> void mapConvert(T t, Map<String, String> map) throws Exception {
		Field[] fields = t.getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			Object val = field.get(t);
			if (val != null) {
				map.put(field.getName(), val.toString());
			}
		}
	}

	// 简单对象转换
	public static <T> void mapConvertObject(T t, Map<String, Object> map) throws Exception {
		Field[] fields = t.getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			Object val = field.get(t);
			if (val != null) {
				map.put(field.getName(), val);
			}
		}
	}

}
